package com.hang.controller;

import com.hang.common.Result;
import com.hang.exception.MyException;
import com.hang.model.dto.base.ConditionDTO;
import com.hang.model.dto.request.FileDeleteDTO;
import com.hang.model.dto.request.FileUploadDTO;
import com.hang.model.dto.request.ModuleConditionDTO;
import com.hang.model.vo.FileInfoListVO;
import com.hang.service.IFileService;
import com.hang.service.ITbFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@Api(tags = "文件上传接口")
@RequestMapping("file")
@RestController
@Slf4j
public class FileController {
    @Resource
    private ITbFileService tbFileService;

    @Resource
    private IFileService fileService;

    @PostMapping("save")
    @ApiOperation(value = "上传保存接口")
    public Result<Object> saveFile(
            @RequestBody @Valid FileUploadDTO uploadDTO
    ){
        //写入文件上传记录表
        try {
            tbFileService.saveFileRecord(uploadDTO);
        }catch (MyException me){
            log.error(me.toString());
            return Result.fail().message(me.getMessage());
        }
        return Result.ok().message("上传成功");
    }

    @PostMapping("upload")
    @ApiOperation(value = "上传文件接口")
    public Result<String> uploadFile(@RequestParam("file") MultipartFile file){
        try {
            String url = fileService.upload(file);
            return Result.ok(url).message("上传成功!");
        }catch (MyException me){
            log.error(me.toString());
            return Result.fail("上传失败").message(me.getMessage());
        }
    }

    @DeleteMapping("delete")
    @ApiOperation(value = "删除文件")
    public Result<Object> deleteFileList(
            @RequestBody @Valid FileDeleteDTO deleteDTO
    ){
        try {
            tbFileService.deleteFileRecord(deleteDTO);
        }catch (MyException me){
            log.error(me.toString());
            return Result.fail().message(me.getMessage());
        }
        return Result.ok().message("删除成功");
    }

    @ApiOperation(value = "查看项目模块的文件列表")
    @PostMapping("getFileListByCondition")
    public Result<FileInfoListVO> getFileListByCondition(
            @RequestBody ModuleConditionDTO conditionDTO
    ){
        FileInfoListVO fileInfoListVO = tbFileService.getFileListByCondition(conditionDTO);
        return Result.ok(fileInfoListVO);
    }
}
